package answer

import (
	"github.com/gin-gonic/gin"

	"com.jiaguyu/logger"

	"com.jiaguyu/model"
	"com.jiaguyu/until"

	"com.jiaguyu/dao/db"
)

func AnswerQuestionListHandle(ctx *gin.Context) {
	question_id, err := until.GetQueryInt64(ctx, "question_id")
	if err != nil {
		logger.Error("get question id failed err:%v", err)
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}
	offset, err := until.GetQueryInt64(ctx, "offset")
	if err != nil {
		logger.Error("get question offset failed err:%v", err)
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}
	limit, err := until.GetQueryInt64(ctx, "limit")
	if err != nil {
		logger.Error("get question limit failed err:%v", err)
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}

	logger.Debug("debugger answer is success qid:%V offset:%v limit:%V", question_id, offset, limit)

	//获取question-ID 对应answer_id的值
	answerIdList, err := db.GetAnswerIdList(question_id, offset, limit)

	if err != nil {
		logger.Error("查询answerID err :%V", err)
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	answerList, err := db.MGetAnswerList(answerIdList)
	if err != nil {
		logger.Error("answerList id faile err:%v", err)
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	var userIdList []int64
	for _, v := range answerList {
		userIdList = append(userIdList, v.AuthorId)
	}

	userInfoList, err := db.GetUserInfoList(userIdList)
	if err != nil {
		logger.Error("获取用户信息失败")
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	apiAnswerList := &model.ApiAnswerList{}
	for _, v := range answerList {
		apiAnswer := &model.ApiAnswer{}
		apiAnswer.Answer = *v
		for _, user := range userInfoList {
			if user.UserId == v.AuthorId {
				apiAnswer.AuthorName = user.UserName
				break
			}
		}
		apiAnswerList.AnswerList = append(apiAnswerList.AnswerList, apiAnswer)
	}

	answerCount, err := db.GetAnswerCount(question_id)
	if err != nil {
		logger.Error("获取用户信息失败")
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	apiAnswerList.TotalCount = int32(answerCount)

	until.ResponseSuccess(ctx, apiAnswerList)
}
